// purchase_scr.c
#include "purchase_scr.h"

static lv_obj_t *TrainNumber_ta = NULL;
static lv_obj_t *date_ta = NULL;
static lv_obj_t *start_ta = NULL;
static lv_obj_t *end_ta = NULL;
static lv_obj_t *scr_purchase = NULL;
static lv_obj_t *result_list = NULL;
static lv_obj_t *return_btn = NULL;

static lv_obj_t *kb = NULL;
// 座位选择相关变量
static lv_obj_t *seat_modal = NULL;
static lv_obj_t *seat_buttons[256] = {NULL};
static Train *selected_train = NULL;
static int selected_seat_type = 0;
static lv_obj_t *active_msgbox = NULL; // 跟踪当前活动的消息框
static lv_obj_t *modal_bg = NULL;      // 模态背景

static void confirm_purchase_cb(lv_event_t *e);
static void list_item_event_cb(lv_event_t *e);

// 创建模态背景
static void create_modal_bg(lv_obj_t *parent)
{
    if (modal_bg) {
        lv_obj_del(modal_bg);
        modal_bg = NULL;
    }
    
    modal_bg = lv_obj_create(parent);
    lv_obj_set_size(modal_bg, LV_PCT(100), LV_PCT(100));
    lv_obj_set_style_bg_opa(modal_bg, LV_OPA_50, 0);
    lv_obj_set_style_bg_color(modal_bg, lv_color_black(), 0);
    lv_obj_set_style_border_width(modal_bg, 0, 0);
    lv_obj_set_style_radius(modal_bg, 0, 0);
    lv_obj_clear_flag(modal_bg, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_add_flag(modal_bg, LV_OBJ_FLAG_CLICKABLE);
    lv_obj_move_foreground(modal_bg);
}

// 输入框事件回调 - 显示键盘
// static void ta_event_cb(lv_event_t *e)
// {
//     lv_event_code_t code = lv_event_get_code(e);
//     lv_obj_t *ta = lv_event_get_target(e);
    
//     if(code == LV_EVENT_CLICKED || code == LV_EVENT_FOCUSED) 
//     {
//         lv_keyboard_set_textarea(kb, ta);
//         lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
//         lv_obj_move_foreground(kb);
//     }
// }
static void ta_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *ta = lv_event_get_target(e);

    if(code == LV_EVENT_FOCUSED) {
        /* 关联键盘并显示 */
        lv_keyboard_set_textarea(kb, ta);   /* kb 为全局 lv_obj_t *kb */
        lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_move_foreground(kb);
    }
    else if(code == LV_EVENT_DEFOCUSED) {
        /* 隐藏键盘 */
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    }
}

// 消息框关闭回调
static void msgbox_close_cb(lv_event_t *e)
{
    lv_obj_t *obj = lv_event_get_target(e);
    lv_obj_del(active_msgbox);
    active_msgbox = NULL;
    
    // 如果模态背景存在且没有其他弹出窗口，删除模态背景
    if (modal_bg && !seat_modal && !active_msgbox) {
        lv_obj_del(modal_bg);
        modal_bg = NULL;
    }
}

// 清除结果列表
static void clear_result_list(void)
{
    lv_obj_clean(result_list);
}

// 添加班次信息到结果列表
static void add_train_to_list(Train *train)
{
    char buffer[512];
    snprintf(buffer, sizeof(buffer), 
             "%s  日期：%s %s-%s %s-%s 票价:%.1f元 余票:%d",
             train->TrainNumber,
             train->date,
             train->start, train->end,
             train->DepartTime, train->ArriveTime,
             train->seats[0].SeatPrice,
             train->seats[0].AvailableSeats);
    
    lv_obj_t *btn = lv_list_add_btn(result_list, NULL, buffer);
    lv_obj_set_user_data(btn, train);
    lv_obj_set_style_text_font(btn, font_chinese, 0);
    lv_obj_add_event_cb(btn, list_item_event_cb, LV_EVENT_CLICKED, NULL);
}

// 关闭座位模态窗口的回调函数
static void close_seat_modal_cb(lv_event_t *e) 
{
    if (seat_modal) {
        lv_obj_del(seat_modal);
        seat_modal = NULL;
        selected_train = NULL;
        selected_seat_type = 0;
        memset(seat_buttons, 0, sizeof(seat_buttons));
    }
    
    // 如果模态背景存在且没有其他弹出窗口，删除模态背景
    if (modal_bg && !active_msgbox) {
        lv_obj_del(modal_bg);
        modal_bg = NULL;
    }
}

// 座位按钮点击事件
static void seat_button_cb(lv_event_t *e)
{
    if (!selected_train ||
        selected_seat_type < 0 || selected_seat_type >= selected_train->seatCount) {
        printf("非法访问\n");
        return;
    }

    int seat_index = (int)(intptr_t)lv_event_get_user_data(e);
    SeatInfo *seat_info = &selected_train->seats[selected_seat_type];
    if (seat_index < 0 || seat_index >= seat_info->TotalSeats ||
        seat_info->SeatStatus[seat_index] != '1') {
        printf("座位不可用\n");
        return;
    }

    char msg[256];
    snprintf(msg, sizeof(msg),
             "确定购买 %s 座位号 %s？\n票价：%.1f 元",
             selected_train->TrainNumber,
             selected_train->seats[selected_seat_type].SeatNumbers[seat_index],
             selected_train->seats[selected_seat_type].SeatPrice);

    // 创建模态背景
    if (!modal_bg) {
        create_modal_bg(lv_layer_top());
    }
    
    static const char *confirm_btns[] = {"确认", "取消", ""};
    lv_obj_t *mbox = lv_msgbox_create(lv_layer_top(), "确认购票", msg, confirm_btns, NULL);
    lv_obj_set_style_text_font(mbox, font_chinese, 0);
    lv_obj_center(mbox);
    active_msgbox = mbox;

    // 保存座位索引到消息框的用户数据
    lv_obj_set_user_data(mbox, (void *)(intptr_t)seat_index);
    lv_obj_add_event_cb(mbox, confirm_purchase_cb, LV_EVENT_VALUE_CHANGED, NULL);
}

/* 真正执行购票的业务逻辑（确认框回调） */
static void confirm_purchase_cb(lv_event_t *e)
{
    lv_obj_t *mbox = lv_event_get_current_target(e);
    uint32_t btn_id = lv_msgbox_get_active_btn(mbox);
    
    // 无论确认还是取消，都先关闭消息框
    lv_obj_del(mbox);
    active_msgbox = NULL;

    if (btn_id != 0) {
        // 用户点击了"取消"
        // 如果模态背景存在且没有其他弹出窗口，删除模态背景
        if (modal_bg && !seat_modal) {
            lv_obj_del(modal_bg);
            modal_bg = NULL;
        }
        return;
    }

    // 用户点击了"确认"
    int seat_index = (int)(intptr_t)lv_obj_get_user_data(mbox);

    // 再次检查（防止并发）
    SeatInfo *seat_info = &selected_train->seats[selected_seat_type];
    if (seat_info->SeatStatus[seat_index] != '1') return;

    // 真正购票
    if (!reserveSeat(selected_train, selected_seat_type, seat_index)) return;

    // 把订单加入当前用户
    User *u = findUser(userList, user);
    if (!u) return;

    UserOrder *orders = realloc(u->orders, (u->orderCount + 1) * sizeof(UserOrder));
    if (!orders) return;
    u->orders = orders;

    UserOrder *o = &orders[u->orderCount++];
    strncpy(o->TrainNumber, selected_train->TrainNumber, sizeof(o->TrainNumber));
    strncpy(o->start,        selected_train->start,       sizeof(o->start));
    strncpy(o->end,          selected_train->end,         sizeof(o->end));
    strncpy(o->DepartTime,   selected_train->DepartTime,  sizeof(o->DepartTime));
    strncpy(o->date,         selected_train->date,        sizeof(o->date));
    strncpy(o->ArriveTime,   selected_train->ArriveTime,  sizeof(o->ArriveTime));

    int dh, dm, ah, am;
    sscanf(selected_train->DepartTime, "%d:%d", &dh, &dm);
    sscanf(selected_train->ArriveTime, "%d:%d", &ah, &am);
    int td = dh * 60 + dm, ta = ah * 60 + am;
    if (ta < td) ta += 24 * 60;
    int diff = ta - td;
    snprintf(o->TimeDifference, sizeof(o->TimeDifference), "%02d:%02d", diff / 60, diff % 60);

    o->seatNumber = seat_index + 1;

    // 保存文件并提示
    saveUsersToFile(userList, "userManagement.json");
    saveTrainsToFile(trainList, "bendi.json");

    // 创建模态背景
    if (!modal_bg) {
        create_modal_bg(lv_layer_top());
    }
    
    static const char *ok[] = {"确定", ""};
    lv_obj_t *sbox = lv_msgbox_create(lv_layer_top(), "成功", "购票成功！", ok, NULL);
    lv_obj_set_style_text_font(sbox, font_chinese, 0);
    lv_obj_add_event_cb(sbox, msgbox_close_cb, LV_EVENT_VALUE_CHANGED, NULL);
    // lv_obj_add_event_cb(sbox, msgbox_close_cb, LV_EVENT_DELETE, NULL);
    lv_obj_center(sbox);
    active_msgbox = sbox;

    // 关闭座位选择窗口
    close_seat_modal_cb(NULL);
}

// 显示座位选择界面
static void show_seat_selection(Train *train, int seat_type) 
{
    if (!train || !trainList) 
    {
        printf("错误: 班次或链表数据无效\n");
        return;
    }
    
    // 重新验证train是否仍在链表中
    Train *valid_train = findTrain(trainList, train->TrainNumber);
    if (!valid_train || valid_train != train) 
    {
        printf("错误: 班次数据已过期\n");
        return;
    }
    
    if (!train->seats) {
        printf("错误: 班次座位数据无效\n");
        return;
    }
    
    if (seat_type < 0 || seat_type >= train->seatCount) 
    {
        printf("错误: 座位类型索引越界\n");
        return;
    }
    
    if (!train->seats[seat_type].SeatStatus || !train->seats[seat_type].SeatNumbers) 
    {
        printf("错误: 座位状态或号码数据无效\n");
        return;
    }
    
    selected_train = train;
    selected_seat_type = seat_type;
    
    // 创建模态背景
    create_modal_bg(lv_layer_top());
    
    // 创建模态窗口
    if (seat_modal) 
    {
        lv_obj_del(seat_modal);
        seat_modal = NULL;
    }
    
    seat_modal = lv_obj_create(lv_layer_top());
    lv_obj_set_size(seat_modal, 700, 500);
    lv_obj_center(seat_modal);
    lv_obj_set_style_bg_opa(seat_modal, LV_OPA_COVER, 0);
    lv_obj_set_style_bg_color(seat_modal, lv_color_hex(0x2D2D3A), 0);
    lv_obj_set_style_border_width(seat_modal, 2, 0);
    lv_obj_set_style_border_color(seat_modal, lv_color_white(), 0);
    lv_obj_set_style_radius(seat_modal, 10, 0);
    
    // 标题
    lv_obj_t *title = lv_label_create(seat_modal);
    char title_text[100];
    snprintf(title_text, sizeof(title_text), "选择座位: %s - %.2f元", 
             train->TrainNumber, train->seats[seat_type].SeatPrice);
    lv_label_set_text(title, title_text);
    lv_obj_set_style_text_font(title, font_chinese, 0);
    lv_obj_set_style_text_color(title, lv_color_white(), 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 20);
    
    // 可用座位信息
    lv_obj_t *info_label = lv_label_create(seat_modal);
    char info_text[256];
    snprintf(info_text, sizeof(info_text), "可用座位: %d/%d", 
             train->seats[seat_type].AvailableSeats, train->seats[seat_type].TotalSeats);
    lv_label_set_text(info_label, info_text);
    lv_obj_set_style_text_font(info_label, font_chinese, 0);
    lv_obj_set_style_text_color(info_label, lv_color_white(), 0);
    lv_obj_align(info_label, LV_ALIGN_TOP_LEFT, 20, 60);
    
    // 创建座位网格容器，可滚动
    lv_obj_t *container = lv_obj_create(seat_modal);
    lv_obj_set_size(container, 650, 350);
    lv_obj_align(container, LV_ALIGN_TOP_LEFT, 20, 90);
    lv_obj_set_style_bg_opa(container, LV_OPA_TRANSP, 0);
    lv_obj_set_style_border_width(container, 0, 0);
    lv_obj_set_style_pad_all(container, 10, 0);
    lv_obj_set_flex_flow(container, LV_FLEX_FLOW_ROW_WRAP);
    lv_obj_set_flex_align(container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
    lv_obj_set_scrollbar_mode(container, LV_SCROLLBAR_MODE_AUTO);
    
    // 创建座位按钮
    for (int i = 0; i < train->seats[seat_type].TotalSeats; i++) 
    {
        lv_obj_t *btn = lv_btn_create(container);
        lv_obj_set_size(btn, 50, 30);
        
        // 根据座位状态设置颜色
        if (train->seats[seat_type].SeatStatus[i] == '1') 
        {
            lv_obj_set_style_bg_color(btn, lv_color_hex(0x00FF00), 0); // 绿色-可用
        } 
        else 
        {
            lv_obj_set_style_bg_color(btn, lv_color_hex(0xFF0000), 0); // 红色-不可用
            lv_obj_add_state(btn, LV_STATE_DISABLED); // 禁用不可用座位
        }
        
        // 设置座位号
        lv_obj_t *label = lv_label_create(btn);
        lv_label_set_text(label, train->seats[seat_type].SeatNumbers[i]);
        lv_obj_set_style_text_font(label, font_chinese, 0);
        lv_obj_center(label);
        
        // 添加点击事件
        lv_obj_add_event_cb(btn, seat_button_cb, LV_EVENT_CLICKED, (void*)(intptr_t)i);
        
        seat_buttons[i] = btn;
    }
    
    // 关闭按钮
    lv_obj_t *close_btn = lv_btn_create(seat_modal);
    lv_obj_set_size(close_btn, 100, 40);
    lv_obj_align(close_btn, LV_ALIGN_BOTTOM_RIGHT, -20, -20);
    lv_obj_set_style_bg_color(close_btn, lv_color_hex(0xF44336), 0);
    lv_obj_t *close_label = lv_label_create(close_btn);
    lv_label_set_text(close_label, "关闭");
    lv_obj_set_style_text_font(close_label, font_chinese, 0);
    lv_obj_center(close_label);
    lv_obj_add_event_cb(close_btn, close_seat_modal_cb, LV_EVENT_CLICKED, NULL);
}

// 查询按钮事件回调函数
static void find_btn_event_cb(lv_event_t *e)
{
    const char *train_number = lv_textarea_get_text(TrainNumber_ta);
    const char *date = lv_textarea_get_text(date_ta);
    const char *start = lv_textarea_get_text(start_ta);
    const char *end = lv_textarea_get_text(end_ta);
    
    clear_result_list();
    
    Train *current = trainList->head;
    int found_count = 0;
    
    while (current != NULL) {
        int match = 1;
        
        if (strlen(train_number) > 0 && 
            strstr(current->TrainNumber, train_number) == NULL) {
            match = 0;
        }
        
        if (match && strlen(date) > 0 && 
            strstr(current->date, date) == NULL) {
            match = 0;
        }
        
        if (match && strlen(start) > 0 && 
            strstr(current->start, start) == NULL) {
            match = 0;
        }
        
        if (match && strlen(end) > 0 && 
            strstr(current->end, end) == NULL) {
            match = 0;
        }
        
        if (match) {
            add_train_to_list(current);
            found_count++;
        }
        
        current = current->next;
    }
    
    if (found_count == 0) {
        lv_obj_t *btn = lv_list_add_btn(result_list, NULL, "未找到匹配的班次");
        lv_obj_set_style_text_font(btn, font_chinese, 0);
        lv_obj_add_state(btn, LV_STATE_DISABLED);
    }
}

// 列表项点击事件回调
static void list_item_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    
    if (code == LV_EVENT_CLICKED) {
        lv_obj_t *btn = lv_event_get_target(e);
        Train *train = (Train *)lv_obj_get_user_data(btn);
        
        if (train != NULL) {
            // 显示座位选择界面
            show_seat_selection(train, 0);
        }
    }
}

// 返回按钮事件回调
static void return_btn_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) 
    {
        // 隐藏键盘
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
        
        // 关闭所有可能的消息框
        if (active_msgbox) {
            lv_obj_del(active_msgbox);
            active_msgbox = NULL;
        }
        
        // 关闭座位选择窗口
        if (seat_modal) {
            close_seat_modal_cb(NULL);
        }
        
        // 关闭模态背景
        if (modal_bg) {
            lv_obj_del(modal_bg);
            modal_bg = NULL;
        }
        
        lv_scr_load(scr_main);
    }
}

// 输入框初始化
lv_obj_t *ta_init(lv_obj_t *parent, const char *placeholder, int x, int y)
{
    lv_obj_t *ta = lv_textarea_create(parent);
    lv_textarea_set_placeholder_text(ta, placeholder);
    lv_obj_set_style_text_font(ta, font_chinese, 0);
    lv_obj_set_size(ta, 150, 40);
    lv_textarea_set_max_length(ta, 20);
    lv_textarea_set_one_line(ta, true);
    lv_obj_set_pos(ta, x, y);
    lv_obj_set_style_bg_opa(ta, LV_OPA_50, 0);
    lv_obj_set_style_bg_color(ta, lv_color_black(), 0);
    
    // 添加事件回调，点击时显示键盘
    lv_obj_add_event_cb(ta, ta_event_cb, LV_EVENT_ALL, NULL);
    
    return ta;
}

// 购票界面
void show_ticket_purchase_screen(void)
{

    
    scr_purchase = lv_obj_create(NULL);
    lv_obj_add_style(scr_purchase, &bg_style, 0);
    lv_obj_clear_flag(scr_purchase, LV_OBJ_FLAG_SCROLLABLE);
    lv_scr_load(scr_purchase); 

    TrainNumber_ta = ta_init(scr_purchase, "班次号", 20, 20);
    date_ta = ta_init(scr_purchase, "日期", 190, 20);
    start_ta = ta_init(scr_purchase, "起点", 360, 20);
    end_ta = ta_init(scr_purchase, "终点", 530, 20);
    
    lv_obj_t *find_btn = lv_btn_create(scr_purchase);
    lv_obj_set_size(find_btn, 100, 60);
    lv_obj_set_pos(find_btn, 700, 18);
    lv_obj_set_style_bg_color(find_btn, lv_color_hex(0x4CAF50), 0);
    lv_obj_set_style_radius(find_btn, 10, 0);
    
    lv_obj_t *find_label = lv_label_create(find_btn);
    lv_label_set_text(find_label, "查询");
    lv_obj_set_style_text_font(find_label, font_chinese, 0);
    lv_obj_set_style_text_color(find_label, lv_color_white(), 0);
    lv_obj_center(find_label);
    
    lv_obj_add_event_cb(find_btn, find_btn_event_cb, LV_EVENT_CLICKED, NULL);

    result_list = lv_list_create(scr_purchase);
    lv_obj_set_size(result_list, 1020, 400);
    lv_obj_set_pos(result_list, 20, 80);
    lv_obj_set_style_border_width(result_list, 1, 0);
    lv_obj_set_style_border_color(result_list, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_style_radius(result_list, 10, 0);

    return_btn = lv_btn_create(scr_purchase);
    lv_obj_set_size(return_btn, 150, 80);
    lv_obj_set_pos(return_btn, 900, 0);
    lv_obj_set_style_bg_color(return_btn, lv_color_hex(0xF44336), 0);
    lv_obj_set_style_radius(return_btn, 10, 0);
    
    lv_obj_t *return_label = lv_label_create(return_btn);
    lv_label_set_text(return_label, "返回界面");
    lv_obj_set_style_text_font(return_label, font_chinese, 0);
    lv_obj_set_style_text_color(return_label, lv_color_white(), 0);
    lv_obj_center(return_label);
    
    lv_obj_add_event_cb(return_btn, return_btn_event_cb, LV_EVENT_CLICKED, NULL);

    // 创建键盘
    kb = lv_keyboard_create(scr_purchase);
    lv_obj_set_size(kb, LV_HOR_RES, LV_VER_RES / 2);
    lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
    lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    lv_obj_set_style_radius(kb, 10, 0);
    
    clear_result_list();
    Train *current = trainList->head;
    while (current != NULL) 
    {
        add_train_to_list(current);
        current = current->next;
    }
}